﻿using LituoPro.constant;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LituoPro.util
{
    public class SerialPortUtil
    {
        private static SerialPort serialPort;



        public static string[] getDevPorts()
        {
            try
            {
                string[] ports = SerialPort.GetPortNames();
                return ports;
            }
            catch (Exception ex)
            {
                MessageBox.Show("无法获取串口列表:" + ex.Message);
                return null;
            }

        }

        public static SerialPort initSerialPort(string portValue)
        {
            if (serialPort == null)
            {
                serialPort = new SerialPort(portValue, 9600, Parity.None, 8, StopBits.One);
            }
            serialPort.ReadTimeout = 2000;
            serialPort.WriteTimeout = 2000;
            return serialPort;
        }

        public static void clearSerialPort()
        {
            serialPort = null;
        }

        public static String openSerialPort(SerialPort serialPort)
        {
            lock (serialPort)
            {
                try
                {
                    serialPort.Open();
                    return SystemConstant.OPEN_SERIAL_PORT_RET_MSG_SUCCESS;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("openSerialPort error:" + ex.Message);
                    return ex.Message;
                }
            }
        }

        public static String closeSerialPort(SerialPort serialPort)
        {
            lock (serialPort)
            {
                try
                {
                    if (serialPort.IsOpen) 
                    {
                        serialPort.Close();
                    } 
                    return SystemConstant.CLOSE_SERIAL_PORT_RET_MSG_SUCCESS;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("CloseSerialPort error:" + ex.Message);
                    return ex.Message;
                }
            }
        }




        public static void sendData(SerialPort serialPort,byte[] bytes)
        {
            lock (serialPort)
            {
                try
                {
                    if (serialPort.IsOpen)
                    {
                        serialPort.Write(bytes, 0, bytes.Length);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("sendData error:" + ex.Message);
                }
            }
        }

    }
}
